package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.room.Room;
import androidx.room.RoomDatabase;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.myapplication.dao.PersonDao;
import com.example.myapplication.model.Person;
import com.example.myapplication.vm.PersonViewModel;

import org.w3c.dom.Text;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    PersonDatabase personDatabase;
    PersonDao personDao;
    Button buttonInsert,buttonUpdate,buttonDelete,buttonClear;
    TextView textView;
    LiveData<List<Person>> allPersonLive;
    PersonViewModel personViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        personViewModel=ViewModelProviders.of(this).get(PersonViewModel.class);
        personDatabase= Room.databaseBuilder(this, PersonDatabase.class,"person_database")
                .allowMainThreadQueries()
                .build();
        personDao=personDatabase.getPersonDao();
        textView=findViewById(R.id.textView);
        buttonInsert=findViewById(R.id.button);
        buttonUpdate=findViewById(R.id.button2);
        buttonClear=findViewById(R.id.button3);
        buttonDelete=findViewById(R.id.button4);
        allPersonLive=personDao.findAllLive();
        personViewModel.getAllPersonLive().observe(this, new Observer<List<Person>>() {
            @Override
            public void onChanged(List<Person> people) {
                StringBuilder text= new StringBuilder();
                for (Person person : people) {
                    text.append("id:").append(person.getId()).append(" name:").append(person.getName()).append(" age:").append(person.getAge()).append(" height:").append(person.getHeight()).append("\n");
                }
                textView.setText(text.toString());
            }
        });

        buttonInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Person p1=new Person(0,"wls","20","175");
                Person p2=new Person(0,"cls","123","465");
               personViewModel.insertPerson(p1,p2);
            }
        });

        buttonClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               personViewModel.clearPerson();
            }
        });


    }


}
